package cn.lg.soar.database.config;

import cn.lg.soar.database.datascope.SoarDataPermissionHandler;
import cn.lg.soar.database.handler.SoarTenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.DataPermissionInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;

/**
 * 多租户、分页、乐观锁
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@RefreshScope
@MapperScan("cn.lg.soar.database.translate.mapper.TranslateMapper")
public class MybatisPlusConfig {

    @Autowired
    private DatabaseProperties propertie;

    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();

        // 多租户插件
        if (propertie.getEnabledTenant()) {
            SoarTenantLineHandler soarTenantLineHandler = new SoarTenantLineHandler();
            interceptor.addInnerInterceptor(new TenantLineInnerInterceptor(soarTenantLineHandler));
        }

        // 数据权限插件
        if (propertie.getEnabledDataPermission()) {
            SoarDataPermissionHandler soarDataPermissionHandler = new SoarDataPermissionHandler();
            interceptor.addInnerInterceptor(new DataPermissionInterceptor(soarDataPermissionHandler));
        }

        // 分页插件
        PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor(propertie.getDbType());
        paginationInnerInterceptor.setOverflow(propertie.getPageOverflow());
        paginationInnerInterceptor.setMaxLimit(propertie.getMaxPageSize());
        interceptor.addInnerInterceptor(paginationInnerInterceptor);

        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());

        return interceptor;
    }

}
